const router = require("koa-router")();

const { handleRequestAsync } = require("../controller/common");
const controller = require("../controller/channel");
const { SuccessModel, ErrorModel } = require("../model/resModel");
const loginCheck = require("../middleware/loginCheck");

// 频道前缀
router.prefix("/channel");

/* 添加频道 */
router.post("/0", loginCheck, async function (ctx, next) {
    console.log("views/channel/post:ctx.request.body=", ctx.request.body);
    await handleRequestAsync(
        ctx,
        controller.addChannel,
        "添加频道成功",
        "添加频道失败",

        // 请求体
        ctx.request.body
    );
});

/* 
删除频道 
DELETE /channel/1234567890
id是动态路由
*/
router.delete("/:id", loginCheck,async function (ctx, next) {
    // 得到动态路由id
    const { id } = ctx.params;
    console.log("views/channel/delete:id=", id);

    const data = await controller.deleteChannel(id);
    console.log("id/data", id, data);

    if (!data.err) {
        ctx.body = new SuccessModel(data, "删除频道成功");
    } else {
        ctx.body = new ErrorModel(data.err, "删除频道失败");
    }
});

/* 修改频道 */
router.put("/:id",loginCheck, async function (ctx, next) {
    try {
        const { id } = ctx.params;
        const reqBoby = ctx.request.body;
        // console.log("reqBoby", reqBoby);

        const data = await controller.updateChannel(id, reqBoby);

        if (!data.err) {
            ctx.body = new SuccessModel(data, "修改频道成功");
        } else {
            ctx.body = new ErrorModel(data.err, "修改频道失败");
        }
    } catch (err) {
        ctx.body = new ErrorModel({ err: "服务器错误" }, "修改频道失败");
    }
});

/* 查询所有频道 */
router.get("/list/0", async function (ctx, next) {
    // console.log("id=", ctx.params);
    const { id } = ctx.params;
    const data = await controller.getAllChannels();

    if (!data.err) {
        ctx.body = new SuccessModel(data, "查询频道列表成功");
    } else {
        ctx.body = new ErrorModel(data.err, "查询频道列表失败");
    }
});

/* 获取频道详情 */
router.get("/:id", async function (ctx, next) {
    const { id } = ctx.params;
    ctx.body = new SuccessModel({ id }, "查询频道详情成功");
});

module.exports = router;
